package com.optionexplorer.data;

import java.util.logging.Logger;

import com.optionexplorer.util.StringUtils;
import com.optionexplorer.util.NetUtils;

public class YahooStockQuoteImpl implements QuoteIfc {

	private static final Logger Log = Logger.getLogger(YahooStockQuoteImpl.class.getName());
	private static final String QUOTE_URL = "http://finance.yahoo.com/q?s=";
	private String ticker = null;
	
	public YahooStockQuoteImpl(String str) {
		this.ticker = str;
	}
	
	public float getQuote() {
		String url = QUOTE_URL + this.ticker;
		float quoteVal = 0;
		StringBuilder sb = NetUtils.getPageFromWeb(url);
		int index1, index2 = 0;
		
		index1 = sb.indexOf("Last Trade");
		if (index1 < 0) {
			Log.severe("Could not find the pattern Last Trade in url : " + url);
			return quoteVal;
		}
		
		index1 = sb.indexOf("<td", index1);
		index2  = sb.indexOf("</td>", index1);
		String str = sb.substring(index1, index2+4);
		str = StringUtils.stripHTML(str);
		quoteVal = StringUtils.strToFloat(str);
		
		return quoteVal;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		String ticker = "YHOO";
		YahooStockQuoteImpl impl = new YahooStockQuoteImpl(ticker);
		System.out.println(impl.getQuote());
		
	}

}
